package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.AgriculturalForumTopicListAdapter;
import com.isunland.managesystem.adapter.CompanyForumTypeAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CompanyForumTopic;
import com.isunland.managesystem.entity.CompanyForumType;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 对象功能:  农技服务首页
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/16 09:56
 */
public class AgricultureServiceFragment extends BaseListFragment implements View.OnClickListener {
  public static final String EXTRA_TYPE =
      AgricultureServiceFragment.class.getSimpleName() + ".EXTRA_TYPE";
  public static final String EXTRA_TITLE =
      AgricultureServiceFragment.class.getSimpleName() + ".EXTRA_TITLE";
  private CurrentUser mUser;
  private String subCode;
  private TextView tvCollectTitle;
  private TextView tvMyAnswer;
  private TextView tvMyMessage;
  private AgriculturalForumTopicListAdapter mAdapter1;

  @Override public void onStart() {
    super.onStart();
    volleyPostPostCount();//获取待回复数量
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    mUser = CurrentUser.newInstance(getActivity());
    String title = getArguments().getString(EXTRA_TITLE);
    if (title != null) setTitleCustom(title);
    subCode =
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, "");
  }

  private void volleyPostPostCount() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TOPIC_POSTCOUNT);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("topicKindCode",
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, ""));
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        SuccessMessage message = new Gson().fromJson(json, SuccessMessage.class);
        if (message != null && SuccessMessage.SUCCESS.equalsIgnoreCase(message.getResult())) {
          if (!TextUtils.isEmpty(message.getMessage()) && !"0".equalsIgnoreCase(
              message.getMessage())) {
            tvMyAnswer.setText(getString(R.string.myFoot) + "(" + message.getMessage() + ")");
          }
          if (!TextUtils.isEmpty(message.getCause()) && !"0".equalsIgnoreCase(message.getCause())) {
            tvMyMessage.setText(getString(R.string.my_message) + "(" + message.getCause() + ")");
          }
        }
      }
    });
  }

  /**
   * 设置ListView分割线
   */
  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_agriculture_type, mListview,
            false);
    TextView tvMyPublish = (TextView) header.findViewById(R.id.tv_myPublish);
    tvMyAnswer = (TextView) header.findViewById(R.id.tv_myAnswer);
    TextView tvMyCollection = (TextView) header.findViewById(R.id.tv_myCollection);
    TextView tvMyFollow = (TextView) header.findViewById(R.id.tv_myFollow);
    TextView tvMyFriend = (TextView) header.findViewById(R.id.tv_myFriend);
    TextView tvMyCircle = (TextView) header.findViewById(R.id.tv_myCircle);
    tvMyMessage = (TextView) header.findViewById(R.id.tv_myMessage);
    tvCollectTitle = (TextView) header.findViewById(R.id.tv_collectTitle);
    ImageView ivAddCircle = (ImageView) header.findViewById(R.id.iv_addCircle);
    tvMyPublish.setOnClickListener(this);
    tvMyAnswer.setOnClickListener(this);
    tvMyCollection.setOnClickListener(this);
    tvMyFollow.setOnClickListener(this);
    tvMyFriend.setOnClickListener(this);
    tvMyCircle.setOnClickListener(this);
    tvMyMessage.setOnClickListener(this);
    ivAddCircle.setOnClickListener(this);

    mListview.addHeaderView(header);

    //分隔线
    //int padding = MyUtils.dip2px(getActivity().getApplicationContext(), 10);
    //mListview.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
    //mListview.setDividerHeight(padding);
    //mListview.setPadding(padding, 0, padding, padding);
    mListview.setDividerHeight(0);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_query, menu);
    //inflater.inflate(R.menu.menu_forum_publish, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      //case R.id.menu_item_publish:
      //  //发帖
      //  Intent intent = new Intent(getActivity(), AgriculturalTopicPublishActicity.class);
      //  intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_TYPE,
      //      AgriculturalTopicPublishFragment.SELF);
      //  startActivityForResult(intent, 0);
      //  return true;
      case R.id.menu_item_query:
        //查找农作物圈
        Intent query = new Intent(getActivity(), AgricultureCircleActivity.class);
        startActivity(query);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public String getUrl() {
    //return ApiConst.URL_FIRST_MY_LIST;
    return ApiConst.URL_KNOWLEDGEFORUM_POST_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    //params.put("dictFlg", "topicKindDataWJ");
    //params.put("subCode", subCode);

    params.put("subCode", subCode);
    return params.getParams();
  }

  @Override public void resolveResponse(String json) {
    //Type listType = new TypeToken<ArrayList<CompanyForumType>>() {
    //}.getType();
    //List<CompanyForumType> mForumType =
    //    new Gson().<ArrayList<CompanyForumType>>fromJson(json, listType);
    //setAdapter(mForumType);

    CompanyForumTopic topicList = new Gson().fromJson(json, CompanyForumTopic.class);
    ArrayList<CompanyForumTopic.actualObject> mList = new ArrayList<>();
    //具体作物分类下的帖子或我发布的帖子,专家发布的帖子,我收藏的帖子
    mList.addAll(topicList.getData());
    mAdapter1 =
        new AgriculturalForumTopicListAdapter(mActivity, mList, false);//adapter不能为空,header不显示
    setListAdapter(mAdapter1);
  }

  private void setAdapter(List<CompanyForumType> forumType) {
    if (forumType == null) {
      forumType = new ArrayList<>();
    }
    CompanyForumTypeAdapter mAdapter = new CompanyForumTypeAdapter(getActivity(), forumType);
    setListAdapter(mAdapter);
    ((CompanyForumTypeAdapter) getListAdapter()).notifyDataSetChanged();
    String number = mAdapter.getCount() == 0 ? "" : "(" + String.valueOf(mAdapter.getCount()) + ")";
    if ("01".equalsIgnoreCase(subCode)) {
      //农技服务
      tvCollectTitle.setText("收藏的农作物圈 " + number);
    } else if ("02".equalsIgnoreCase(subCode)) {
      //农机服务
      tvCollectTitle.setText("收藏的农机服务圈 " + number);
    }
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    //跳转到二级大豆,玉米详情列表
    //避免点击header时的getitem出现-1的情况.
    //if (position < mListview.getHeaderViewsCount()) return;
    //CompanyForumType item = mAdapter.getItem(position - mListview.getHeaderViewsCount());
    //Intent intent = new Intent(getActivity(), AgricultureServiceSecondActivity.class);
    //intent.putExtra(AgricultureServiceSecondFragment.EXTRA_VALUE, item);
    //intent.putExtra(AgricultureServiceSecondFragment.EXTRA_FFROM,
    //    AgricultureServiceSecondFragment.COLLECT);
    //startActivity(intent);

    //跳转到帖子详情
    if (position < mListview.getHeaderViewsCount()) return;
    CompanyForumTopic.actualObject topicContent =
        mAdapter1.getItem(position - mListview.getHeaderViewsCount());
    Intent intent = new Intent(getActivity(), AgriculturalForumDetailAcrivity.class);
    intent.putExtra(AgriculturalForumDetailFragment.EXTRA_VALUE, topicContent);
    intent.putExtra(AgriculturalForumDetailFragment.EXTRA_FROM, AgriculturalForumListFragment.TYPE);
    startActivity(intent);
    super.onListItemClick(l, v, position, id);
  }

  @Override public void onClick(View view) {
    Intent intent = new Intent();
    Class mClass = null;
    switch (view.getId()) {
      case R.id.tv_myPublish:
        //我发布的话题
        CompanyForumType myPublish = new CompanyForumType();
        myPublish.setName("我发布的话题");
        myPublish.setPublisher(true);
        mClass = AgriculturalForumPagerActivity.class;
        intent.putExtra(AgriculturalForumListFragment.EXTRA_VALUE, myPublish);
        intent.putExtra(AgriculturalForumListFragment.EXTRA_FROM,
            AgriculturalForumListFragment.SELF);
        intent.putExtra(AgriculturalForumListFragment.EXTRA_JOBNO, mUser.getJobNumber());
        break;
      case R.id.tv_myAnswer:
        //我的回复
        mClass = AgriculturalForumMyReplyListActivity.class;
        intent.putExtra(AgriculturalForumMyReplyListFragment.EXTRA_JOBNO, mUser.getJobNumber());
        break;
      case R.id.tv_myCollection:
        //我的收藏: 收藏的帖子,收藏的分类
        mClass = AgriculturalMyCollectListActivity.class;
        intent.putExtra(AgriculturalForumListFragment.EXTRA_JOBNO, mUser.getJobNumber());
        //                intent.putExtra(AgriculturalForumListFragment.EXTRA_FROM, AgriculturalForumListFragment.COLLECT);
        break;
      case R.id.tv_myFollow:
        //我关注的专家
        mClass = MyAttentExpertListActivity.class;
        break;
      case R.id.tv_myFriend:
        //我的好友
        mClass = AgriculturalMyFriendListActivity.class;
        break;
      case R.id.tv_myCircle:
        //我的圈子
        mClass = AgriculturalMyCircleListActivity.class;
        break;
      case R.id.tv_myMessage:
        //我的消息
        mClass = AgriculturalMyMessageListActivity.class;
        break;
      case R.id.iv_addCircle:
        //添加收藏农作物圈,跳转到所有农作物圈
        mClass = AgricultureCircleActivity.class;
        break;
      default:
        break;
    }
    intent.setClass(getActivity(), mClass);
    startActivity(intent);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    volleyPost();
  }

  public static Fragment newInstance(String title) {
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_TITLE, title);
    AgricultureServiceFragment fragment = new AgricultureServiceFragment();
    fragment.setArguments(bundle);
    return fragment;
  }
}
